package com.aos.service.user.impl;

import com.aos.dao.UserDao;
import com.aos.entity.Role;
import com.aos.entity.User;
import com.aos.exception.BusinessException;
import com.aos.exception.ResultStatus;
import com.aos.service.user.UserService;
import com.aos.util.SystemUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("UserService")
public class UserServiceImpl implements UserService {

    private static Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    UserDao userDao;

    @Override
    public User checkUser(String userName, String password) {

        System.out.println("========开始校验用户是否存在========");
        System.out.println("========userName:" + userName);
        System.out.println("========password:" + password);
        //首先校验该用户在数据库中是否存在
        User existUser = userDao.findByUsername(userName);
        if (existUser == null){
            log.debug("用户名不存在！");
            throw new BusinessException("该用户名不存在，请检查！", ResultStatus.fail.toString());
        }

        System.out.println("========开始校验密码是否正确========");
        //校验密码是否正确
        //BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //String hash = encoder.encode(password);
        //User user = userDao.findByUsernameAndPasswordAndServiceid(userName,hash,serviceId);
        //if(!encoder.matches(password,existUser.getPassword()))
        // MD5校验密码
        if(!existUser.getPassword().equals(DigestUtils.md5Hex(password + "{" + existUser.getSalt() + "}")))
        {

            throw new BusinessException("输入密码错误，请检查！", ResultStatus.fail.toString());
        }

//        System.out.println("apaceh盐值加密====id：" + DigestUtils.md5Hex(password + "{" + existUser.getSalt() + "}"));
//        System.out.println("security盐值加密====id：" + new Md5PasswordEncoder().encodePassword(password,existUser.getSalt()));
        System.out.println("用户校验成功====id：" + existUser.getUid());
        System.out.println("用户校验成功====userName：" + userName);
        return existUser;
    }

    @Override
    public int insertUser(String userName,String realName, String password, String serviceId,Long uid,String salt) {
        //首先校验该新增用户名是否已存在，存在则提示
        User existUser = userDao.findByUsername(userName);
        if (existUser != null){
            throw new BusinessException("该用户名已存在，无法新增！", ResultStatus.fail.toString());
        }

        //不存在则为新用户，查询数据库id最大值，加1即为该用户id
        //Long uid = (long)(userDao.getUserByMaxUid().getUid() + 1);
        //Long uid = userDao.getUserByMaxUid() + 1 ;

        System.out.println("取得的用户id====uid：" + uid);

        System.out.println("========开始执行用户新增操作========");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
        //执行新增操作
        //String hash = new BCryptPasswordEncoder().encode(password);
        String newPassword = SystemUtils.getPasswordEncoder(password, salt);
        int count = userDao.insertUserByUid(uid,userName,realName,newPassword,serviceId,date,salt);
        return count;
    }

    @Override
    public int updateUser(String userName, String realName, String password, String serviceId,Long uid,String salt) {
        //首先校验该用户名是否已存在，不在则提示
        User existUser = new User();
        if(uid == 0 || uid == null)//根据username查询。和根据uid查询效果一样
        {
            existUser = userDao.findByUsername(userName);;
        }
        else //根据uid查询
        {
            existUser = userDao.findByUid(uid);
        }

        if (existUser == null){
            throw new BusinessException("该用户名不存在，无法修改信息，请确认！", ResultStatus.fail.toString());
        }

        //存在则修改用户信息
        System.out.println("========开始执行用户修改操作========");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
        //执行新增操作
        //String hash = new BCryptPasswordEncoder().encode(password);
        String newPassword = SystemUtils.getPasswordEncoder(password, salt);
        System.out.println("========uid:["+ existUser.getUid() + "]");
        System.out.println("========password:["+ password + "]");
        System.out.println("========realName:["+ realName + "]");
        System.out.println("========date:["+ date + "]");
        System.out.println("========password:["+ password + "]");

        int count = userDao.updateUserByUid(existUser.getUid(),newPassword,realName,date,salt);
        return count;
    }

    @Override
    public int deleteUser(String userName, String serviceId,Long uid) {
        //首先校验该用户名是否已存在，不在则提示
        User existUser = new User();
        if(uid == 0 || uid == null)//根据username查询。和根据uid查询效果一样
        {
            existUser = userDao.findByUsername(userName);;
        }
        else    //根据uid查询
        {
            existUser = userDao.findByUid(uid);
        }

        if (existUser == null){
            throw new BusinessException("该用户名不存在，无法删除信息，请确认！", ResultStatus.fail.toString());
        }

        //存在则修改用户信息
        System.out.println("========开始执行用户删除操作========");
        int count = userDao.deleteUserByUid(existUser.getUid());
        return count;
    }
}
